package com.qsmx.qingqiuticket.app.delegate.back.camera;

import android.Manifest;
import android.app.Dialog;
import android.hardware.usb.UsbDevice;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageCaptureException;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.common.util.concurrent.ListenableFuture;
import com.herohan.uvcapp.CameraHelper;
import com.herohan.uvcapp.ICameraHelper;

import androidx.camera.core.ImageCapture;

import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.util.dimen.DimenUtil;
import com.qsmx.qingqiuticket.app.MainActivity;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegateCameraTestBinding;
import com.qsmx.qingqiuticket.app.delegate.HomeLoginMemDelegate;
import com.qsmx.qingqiuticket.app.delegate.back.camera.adapter.ImgAdapter;
import com.qsmx.qingqiuticket.app.util.DownloadUtil;
import com.qsmx.qingqiuticket.app.util.FileUtil;
import com.qsmx.qingqiuticket.app.util.SaveHelper;
import com.qsmx.qingqiuticket.app.view.diooto.Diooto;
import com.qsmx.qingqiuticket.app.view.diooto.config.DiootoConfig;
import com.serenegiant.opengl.renderer.MirrorMode;
import com.serenegiant.usb.Size;
import com.serenegiant.utils.UriHelper;
import com.serenegiant.widget.AspectRatioSurfaceView;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;

import me.panpf.sketch.SketchImageView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;


@RuntimePermissions
public class CameraTestDelegate extends AtmosDelegate {

    private DelegateCameraTestBinding mBindView;

    private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;

    @Override
    public Object setLayout() {
        return R.layout.delegate_camera_test;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mBindView = DelegateCameraTestBinding.bind(rootView);
        FileUtil.deleteFolderFile(SaveHelper.getSavePhotoParentPath("test"));

        startCamera();

        onClick();
    }

    private void onClick() {

        mBindView.tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getSupportDelegate().pop();
            }
        });

        mBindView.tvTurnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rotateBy(90);
            }
        });

        mBindView.tvCameraOrientation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flipOrientation();
            }
        });

        mBindView.tvTakePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                takePicture();
            }
        });

        mBindView.tvOpenPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File directory = new File(SaveHelper.getSavePhotoParentPath("test"));
                if (directory.exists()) {
                    File[] files = directory.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            return name.toLowerCase().endsWith(".png")
                                    || name.toLowerCase().endsWith(".jpg")
                                    || name.toLowerCase().endsWith(".jpeg"); // 可以根据需要添加更多格式
                        }
                    });

                    if (files != null && files.length > 0) {
                        // 打开第一个图片文件
                        List<String> filesPath = new ArrayList<>();
                        for (int i = 0; i < files.length; i++) {
                            filesPath.add(files[i].getAbsolutePath());
                        }

                        showOpenImgDialog(filesPath);
                    } else {
                        Toast.makeText(getContext(), "没有找到图片文件", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "没有拍照", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void showOpenImgDialog(List<String> imgList) {
        Dialog imgDialog = new Dialog(getContext(), com.qsmx.core.R.style.dialog);
        imgDialog.setCancelable(false);
        imgDialog.show();
        Window window = imgDialog.getWindow();
        window.setContentView(R.layout.dialog_show_img);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);

        window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT);

        AppCompatTextView tvCancel = window.findViewById(R.id.tv_back_now);

        RecyclerView rlvImg = window.findViewById(R.id.rlv_pic);
        ImgAdapter imgAdapter = new ImgAdapter(getContext());
        LinearLayoutManager manager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        rlvImg.setLayoutManager(manager);
        rlvImg.setAdapter(imgAdapter);
        imgAdapter.setImgs(imgList);

        imgAdapter.setonItemClickListener(new ImgAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                String[] array = (String[]) imgList.toArray(new String[imgList.size()]);
                View[] views = new View[imgList.size()];

                Diooto diooto = new Diooto(getContext())
                        .indicatorVisibility(View.VISIBLE)
                        .urls(array)
                        .type(DiootoConfig.PHOTO)
                        .immersive(true)
                        .position(position, 0)
                        .views(views)
                        .loadPhotoBeforeShowBigImage(new Diooto.OnLoadPhotoBeforeShowBigImageListener() {
                            @Override
                            public void loadView(SketchImageView sketchImageView, int position) {
                                sketchImageView.displayImage(imgList.get(position));
                                sketchImageView.setOnLongClickListener(new View.OnLongClickListener() {
                                    @Override
                                    public boolean onLongClick(View v) {
                                        return false;
                                    }
                                });
                            }
                        }).start();
            }
        });


        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgDialog.dismiss();
            }
        });
    }

    //旋转摄像头
    private void rotateBy(int angle) {
    }

    private void flipOrientation() {
    }

    public void takePicture() {
//        if (mIsRecording) {
//            return;
//        }
//
//        try {
//            File file = new File(SaveHelper.getSavePhotoPath("test"));
//            ImageCapture.OutputFileOptions options =
//                    new ImageCapture.OutputFileOptions.Builder(file).build();
//            mCameraHelper.takePicture(options, new ImageCapture.OnImageCaptureCallback() {
//                @Override
//                public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
//                    Toast.makeText(getContext(),
//                            "save \"" + UriHelper.getPath(getContext(), outputFileResults.getSavedUri()) + "\"",
//                            Toast.LENGTH_SHORT).show();
//                }
//
//                @Override
//                public void onError(int imageCaptureError, @NonNull String message, @Nullable Throwable cause) {
//                    Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
//                }
//            });
//        } catch (Exception e) {
//        }

        startCamera();
    }

    private void startCamera() {
        CameraTestDelegatePermissionsDispatcher.startCheckCameraWithCheck(this);
    }

    private void initCamera() {
        cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext());
        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                CameraSelector cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA; // 使用后置摄像头

                ImageCapture imageCapture = new ImageCapture.Builder()
                        .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
                        .build();

                cameraProvider.unbindAll();
                cameraProvider.bindToLifecycle(this, cameraSelector, imageCapture);

                // 设置输出文件选项
                File photoFile = new File(SaveHelper.getSavePhotoPath("test"));
                ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(photoFile).build();

                // 拍照并保存
                imageCapture.takePicture(outputFileOptions, ContextCompat.getMainExecutor(requireContext()), new androidx.camera.core.ImageCapture.OnImageSavedCallback() {
                    @Override
                    public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                        // 照片保存成功，可以在这里处理保存的文件，例如显示一个Toast消息或者将其显示在ImageView中
//                        Uri photoUri = Uri.fromFile(outputFileResults.getSavedUri());
                        showLongToast("拍照成功，保存路径：" + photoFile.getAbsolutePath());
                    }

                    @Override
                    public void onError(@NonNull ImageCaptureException exception) {
                        // 处理错误，例如显示一个Toast消息
                    }
                });
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            }
        }, ContextCompat.getMainExecutor(requireContext()));
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO})
    void startCheckCamera() {
        initCamera();
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO})
    void onFileRational(PermissionRequest request) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        CameraTestDelegatePermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
